<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="日期" prop="recordDate">
          <el-date-picker
            v-model="queryParams.recordDate"
            class="!w-[240px]"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="关键字" prop="salesmanName">
          <el-input
            v-model="queryParams.salesmanName"
            placeholder="业务员/填写人/被保人/车牌号/投保公司"
            style="width: 320px"
            clearable
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <!--        <el-form-item label="填写人" prop="userName">-->
        <!--          <el-input-->
        <!--            v-model="queryParams.userName"-->
        <!--            placeholder="填写人"-->
        <!--            clearable-->
        <!--            @keyup.enter="handleQuery()"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="车牌号" prop="chepaihao">-->
        <!--          <el-input-->
        <!--            v-model="queryParams.chepaihao"-->
        <!--            placeholder="车牌号"-->
        <!--            clearable-->
        <!--            @keyup.enter="handleQuery()"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <el-form-item label="付款状态" prop="status">
          <el-select v-model="queryParams.isPay" placeholder="全部" clearable class="!w-[150px]">
            <el-option
              v-for="item in isPayOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['system:sysLedger:add']" type="success" @click="handleOpenDialog()">
          <template #icon>
            <Plus />
          </template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['system:sysLedger:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon>
            <Delete />
          </template>
          删除
        </el-button>
        <el-button
          v-hasPerm="'system:sysLedger:export'"
          type="info"
          icon="download"
          @click="handleExport"
        >
          导出
        </el-button>

        <!-- 统计数据显示 -->
        <div class="ledger-count-info">
          车险保费：{{ ledgerCountVO.chexianCount }}￥&nbsp;&nbsp;&nbsp;&nbsp;非车保费：{{
            ledgerCountVO.feicheCount
          }}￥
        </div>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          key="createTime"
          label="填写时间"
          prop="createTime"
          min-width="200"
          align="center"
        />
        <!--        <el-table-column-->
        <!--            key="userId"-->
        <!--            label="用户id"-->
        <!--            prop="userId"-->
        <!--            min-width="150"-->
        <!--            align="center"-->
        <!--        />-->
        <el-table-column
          key="userName"
          label="填写人"
          prop="userName"
          min-width="150"
          align="center"
        />
        <el-table-column key="isPay" label="付款状态" prop="isPay" min-width="160" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.isPay" @change="handleIsPayChange(scope.row)">
              <el-option
                v-for="item in isPayOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column key="type" label="扣税" prop="type" min-width="80" align="center">
          <template #default="scope">
            <DictLabel v-model="scope.row.type" code="is_type" />
          </template>
        </el-table-column>
        <el-table-column
          key="recordDate"
          label="日期"
          prop="recordDate"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="salesmanName"
          label="业务员"
          prop="salesmanName"
          min-width="150"
          align="center"
        />

        <el-table-column
          key="beibaoxianren"
          label="被保险人"
          prop="beibaoxianren"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="chepaihao"
          label="车牌号"
          prop="chepaihao"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="toubaogongshi"
          label="投保公司"
          prop="toubaogongshi"
          min-width="250"
          align="center"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          key="qiangxian"
          label="强险"
          prop="qiangxian"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="shangyexian"
          label="商业险"
          prop="shangyexian"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="chechuanxian"
          label="车船税"
          prop="chechuanxian"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="jiachengxian"
          label="驾乘险"
          prop="jiachengxian"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="qiangxianzhengce"
          label="强险政策"
          prop="qiangxianzhengce"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="shangyezhengce"
          label="商业政策"
          prop="shangyezhengce"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="jiachengxianzhengce"
          label="驾乘险政策"
          prop="jiachengxianzhengce"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="qiangxianfandian"
          label="强险返点"
          prop="qiangxianfandian"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="shangyefandian"
          label="商业返点"
          prop="shangyefandian"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="jiachengfandian"
          label="驾乘返点"
          prop="jiachengfandian"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="fujiajiangli"
          label="附加奖励"
          prop="fujiajiangli"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="yewuyuanjiangli"
          label="业务员奖励"
          prop="yewuyuanjiangli"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="shouxufei"
          label="手续费汇总"
          prop="shouxufei"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="yingshou"
          label="应收"
          prop="yingshou"
          min-width="150"
          align="center"
        />
        <el-table-column key="lirun" label="利润" prop="lirun" min-width="150" align="center" />
        <el-table-column
          key="fangeiyewuyuan"
          label="返给业务员"
          prop="fangeiyewuyuan"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="toubaorenshoujihao"
          label="投保人手机号"
          prop="toubaorenshoujihao"
          min-width="150"
          align="center"
        />
        <!--        <el-table-column-->
        <!--            key="beizhu"-->
        <!--            label="备注"-->
        <!--            prop="beizhu"-->
        <!--            min-width="150"-->
        <!--            align="center"-->
        <!--        />-->
        <el-table-column fixed="right" align="center" label="操作" width="140">
          <template #default="scope">
            <el-button
              v-hasPerm="['system:sysLedger:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon>
                <Edit />
              </template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['system:sysLedger:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon>
                <Delete />
              </template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 流水台账表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="1200px"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <!-- 付款状态 -->
          <el-col :span="8">
            <el-form-item label="付款状态" prop="isPay">
              <Dict
                v-model="formData.isPay"
                code="is_pay"
                placeholder="请选择付款状态"
                style="width: 276px"
                :clearable="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="扣税" prop="type">
              <Dict
                v-model="formData.type"
                code="is_type"
                placeholder="请选择扣税状态"
                style="width: 276px"
                :clearable="false"
              />
            </el-form-item>
          </el-col>
          <!-- 日期 -->
          <el-col :span="8">
            <el-form-item label="日期" prop="recordDate">
              <el-date-picker
                v-model="formData.recordDate"
                type="date"
                placeholder="日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 业务员 -->
          <el-col :span="8">
            <el-form-item label="业务员" prop="salesmanName">
              <el-input
                v-model="formData.salesmanName"
                placeholder="业务员"
                maxlength="32"
                show-word-limit
                clearable
              />
            </el-form-item>
          </el-col>

          <!-- 被保险人 -->
          <el-col :span="8">
            <el-form-item label="被保险人" prop="beibaoxianren">
              <el-input
                v-model="formData.beibaoxianren"
                placeholder="被保险人"
                maxlength="32"
                show-word-limit
                clearable
              />
            </el-form-item>
          </el-col>

          <!-- 车牌号 -->
          <el-col :span="8">
            <el-form-item label="车牌号" prop="chepaihao">
              <el-input
                v-model="formData.chepaihao"
                placeholder="车牌号"
                maxlength="32"
                show-word-limit
                clearable
              />
            </el-form-item>
          </el-col>

          <!-- 投保公司 -->
          <el-col :span="8">
            <el-form-item label="投保公司" prop="toubaogongshi">
              <el-input
                v-model="formData.toubaogongshi"
                placeholder="投保公司"
                maxlength="32"
                show-word-limit
                clearable
              />
            </el-form-item>
          </el-col>

          <!-- 强险 -->
          <el-col :span="8">
            <el-form-item label="强险" prop="qiangxian">
              <el-input-number
                v-model="formData.qiangxian"
                placeholder="强险"
                :controls="false"
                :precision="2"
                maxlength="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 商业险 -->
          <el-col :span="8">
            <el-form-item label="商业险" prop="shangyexian">
              <el-input-number
                v-model="formData.shangyexian"
                placeholder="商业险"
                :controls="false"
                :precision="2"
                maxlength="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 车船税 -->
          <el-col :span="8">
            <el-form-item label="车船税" prop="chechuanxian">
              <el-input-number
                v-model="formData.chechuanxian"
                placeholder="车船税"
                :controls="false"
                :precision="2"
                maxlength="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 驾乘险 -->
          <el-col :span="8">
            <el-form-item label="驾乘险" prop="jiachengxian">
              <el-input-number
                v-model="formData.jiachengxian"
                placeholder="驾乘险"
                :controls="false"
                :precision="2"
                maxlength="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 强险政策 -->
          <el-col :span="8">
            <el-form-item label="强险政策" prop="qiangxianzhengce">
              <el-input-number
                v-model="formData.qiangxianzhengce"
                placeholder="强险政策"
                :controls="false"
                :precision="6"
                maxlength="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 商业政策 -->
          <el-col :span="8">
            <el-form-item label="商业政策" prop="shangyezhengce">
              <el-input-number
                v-model="formData.shangyezhengce"
                placeholder="商业政策"
                :controls="false"
                :precision="6"
                maxlength="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 驾乘险政策 -->
          <el-col :span="8">
            <el-form-item label="驾乘险政策" prop="jiachengxianzhengce">
              <el-input-number
                v-model="formData.jiachengxianzhengce"
                placeholder="驾乘险政策"
                :controls="false"
                :precision="6"
                maxlength="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 强险返点 -->
          <el-col :span="8">
            <el-form-item label="强险返点" prop="qiangxianfandian">
              <el-input-number
                v-model="formData.qiangxianfandian"
                placeholder="强险返点"
                :controls="false"
                :precision="6"
                maxlength="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 商业返点 -->
          <el-col :span="8">
            <el-form-item label="商业返点" prop="shangyefandian">
              <el-input-number
                v-model="formData.shangyefandian"
                placeholder="商业返点"
                :controls="false"
                :precision="6"
                maxlength="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 驾乘返点 -->
          <el-col :span="8">
            <el-form-item label="驾乘返点" prop="jiachengfandian">
              <el-input-number
                v-model="formData.jiachengfandian"
                placeholder="驾乘返点"
                :controls="false"
                :precision="6"
                maxlength="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 附加奖励 -->
          <el-col :span="8">
            <el-form-item label="附加奖励" prop="fujiajiangli">
              <el-input-number
                v-model="formData.fujiajiangli"
                placeholder="附加奖励"
                :controls="false"
                :precision="2"
                maxlength="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 业务员奖励 -->
          <el-col :span="8">
            <el-form-item label="业务员奖励" prop="yewuyuanjiangli">
              <el-input-number
                v-model="formData.yewuyuanjiangli"
                placeholder="业务员奖励"
                :controls="false"
                :precision="2"
                maxlength="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 手续费汇总 -->
          <el-col :span="8">
            <el-form-item label="手续费汇总" prop="shouxufei">
              <el-input-number
                v-model="formData.shouxufei"
                placeholder="手续费汇总（系统计算）"
                :controls="false"
                :precision="2"
                maxlength="10"
                disabled
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 应收 -->
          <el-col :span="8">
            <el-form-item label="应收" prop="yingshou">
              <el-input-number
                v-model="formData.yingshou"
                placeholder="应收（系统计算）"
                :controls="false"
                :precision="4"
                maxlength="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 利润 -->
          <el-col :span="8">
            <el-form-item label="利润" prop="lirun">
              <el-input-number
                v-model="formData.lirun"
                placeholder="利润（系统计算）"
                :controls="false"
                :precision="2"
                maxlength="10"
                disabled
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <!-- 返给业务员 -->
          <el-col :span="8">
            <el-form-item label="返给业务员" prop="fangeiyewuyuan">
              <el-input
                v-model="formData.fangeiyewuyuan"
                placeholder="返给业务员（系统计算）"
                :controls="false"
                :precision="2"
                maxlength="10"
                disabled
              />
            </el-form-item>
          </el-col>

          <!-- 投保人手机号 -->
          <el-col :span="8">
            <el-form-item label="投保人手机号" prop="toubaorenshoujihao">
              <el-input
                v-model="formData.toubaorenshoujihao"
                placeholder="投保人手机号"
                maxlength="32"
                show-word-limit
                clearable
              />
            </el-form-item>
          </el-col>

          <!-- 备注 - 单独一行 -->
          <el-col :span="24">
            <el-form-item label="备注" prop="beizhu">
              <el-input
                v-model="formData.beizhu"
                type="textarea"
                placeholder="备注"
                maxlength="500"
                rows="3"
                style="width: 100%"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="footer-container">
          <span class="total-sum-text">总保费：{{ totalSum }}</span>

          <span class="total-sum-text1">
            系统计算应收
            <el-switch
              v-model="kaiguan"
              class="ml-2"
              inline-prompt
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              active-text="开"
              inactive-text="关"
              size="large"
            />
          </span>

          <div class="dialog-footer">
            <el-button type="primary" :disabled="loading" @click="handleSubmit()">确定</el-button>
            <el-button @click="handleCloseDialog()">取消</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import SysLedgerAPI, {
  LedgerCountVO,
  SysLedgerForm,
  SysLedgerPageQuery,
  SysLedgerPageVO,
} from "@/api/system/sys-ledger";
import Decimal from "decimal.js";

defineOptions({
  name: "SysLedger",
  inheritAttrs: false,
});
// 假设付款状态的选项如下
const isPayOptions = [
  { label: "未付款", value: "未付款" },
  { label: "付款中", value: "付款中" },
  { label: "已付款", value: "已付款" },
];
const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const ledgerCountVO = ref<LedgerCountVO>({});

const loading = ref(false);
const kaiguan = ref(true);
const removeIds = ref<number[]>([]);
let recordDates = ref<[string, string]>([getToday(), getToday()]);
const total = ref(0);
let totalSum = ref<string>("0.00");

const queryParams = reactive<SysLedgerPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 流水台账表格数据
const pageData = ref<SysLedgerPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 流水台账表单数据
const formData = reactive<SysLedgerForm>({
  type: 1,
  isPay: "未付款",
  recordDate: getToday(),
});
// 自动计算手续费汇总
const calculateShouxufei = () => {
  const type = Number(formData.type); // 确保转换为数字类型
  let qiangxian = formData.qiangxian || 0;
  const qiangxianzhengce = formData.qiangxianzhengce || 0;
  let shangyexian = formData.shangyexian || 0;
  const shangyezhengce = formData.shangyezhengce || 0;
  let jiachengxian = formData.jiachengxian || 0;
  const jiachengxianzhengce = formData.jiachengxianzhengce || 0;
  const fujiajiangli = formData.fujiajiangli || 0;
  if (type === 1) {
    if (qiangxian > 0) {
      qiangxian = (qiangxian / 1.06) * qiangxianzhengce;
    }
    if (shangyexian > 0) {
      shangyexian = (shangyexian / 1.06) * shangyezhengce;
    }
    if (jiachengxian > 0) {
      jiachengxian = (jiachengxian / 1.06) * jiachengxianzhengce;
    }
    let value = qiangxian + shangyexian + jiachengxian;
    const result = new Decimal(value).toFixed(2);
    formData.shouxufei = parseFloat(result);
  } else {
    if (qiangxian > 0) {
      qiangxian = qiangxian * qiangxianzhengce;
    }
    if (shangyexian > 0) {
      shangyexian = shangyexian * shangyezhengce;
    }
    if (jiachengxian > 0) {
      jiachengxian = jiachengxian * jiachengxianzhengce;
    }
    let value = qiangxian + shangyexian + jiachengxian;
    const result = new Decimal(value).toFixed(2);
    formData.shouxufei = parseFloat(result);
  }
  formData.shouxufei = formData.shouxufei + fujiajiangli;
};

watch(
  () => [
    formData.type,
    formData.qiangxian,
    formData.qiangxianzhengce,
    formData.shangyexian,
    formData.shangyezhengce,
    formData.jiachengxian,
    formData.jiachengxianzhengce,
    formData.fujiajiangli,
  ],
  () => {
    calculateShouxufei();
  }
);

// 自动计算利润
const calculateLiRun = () => {
  const type = Number(formData.type); // 确保转换为数字类型
  let yingshou = formData.yingshou || 0;
  let qiangxian = formData.qiangxian || 0;
  let shangyexian = formData.shangyexian || 0;
  let jiachengxian = formData.jiachengxian || 0;
  let chechuanxian = formData.chechuanxian || 0;
  let qiangxianzhengce = formData.qiangxianzhengce || 0;
  let shangyezhengce = formData.shangyezhengce || 0;
  let jiachengxianzhengce = formData.jiachengxianzhengce || 0;
  let fujiajiangli = formData.fujiajiangli || 0;
  if (type === 1) {
    //=Q2-(F2-(F2/1.06*J2)+G2-(G2/1.06*K2)+I2-(I2/1.06*L2)+H2)+U2
    qiangxian = qiangxian - (qiangxian / 1.06) * qiangxianzhengce;
    shangyexian = shangyexian - (shangyexian / 1.06) * shangyezhengce;
    jiachengxian = jiachengxian - (jiachengxian / 1.06) * jiachengxianzhengce;
    let tempValue = qiangxian + shangyexian + jiachengxian + chechuanxian;
    let value = yingshou - tempValue + fujiajiangli;
    const result = new Decimal(value).toFixed(2);
    formData.lirun = parseFloat(result);
  } else {
    //=Q2-(F2*(1-J2)+G2*(1-K2)+I2*(1-L2)+H2-U2)
    qiangxian = qiangxian * (1 - qiangxianzhengce);
    shangyexian = shangyexian * (1 - shangyezhengce);
    jiachengxian = jiachengxian * (1 - jiachengxianzhengce);
    let tempValue = qiangxian + shangyexian + jiachengxian + chechuanxian - fujiajiangli;
    let value = yingshou - tempValue;
    const result = new Decimal(value).toFixed(2);
    formData.lirun = parseFloat(result);
  }
};
// 监听利润相关的字段
watch(
  () => [
    formData.type,
    formData.yingshou,
    formData.qiangxian,
    formData.shangyexian,
    formData.jiachengxian,
    formData.chechuanxian,
    formData.qiangxianzhengce,
    formData.shangyezhengce,
    formData.jiachengxianzhengce,
    formData.fujiajiangli,
  ],
  () => {
    calculateLiRun();
  }
);
// 自动计算应收
const calculateYingShou = () => {
  const type = Number(formData.type); // 确保转换为数字类型
  let qiangxian = formData.qiangxian || 0;
  let shangyexian = formData.shangyexian || 0;
  let jiachengxian = formData.jiachengxian || 0;
  const chechuanxian = formData.chechuanxian || 0;
  const qiangxianfandian = formData.qiangxianfandian || 0;
  const shangyefandian = formData.shangyefandian || 0;
  const jiachengfandian = formData.jiachengfandian || 0;
  const yewuyuanjiangli = formData.yewuyuanjiangli || 0;

  let value = 0;
  if (type === 1) {
    //=F2-(F2/1.06*M2)+G2-(G2/1.06*N2)+I2-(I2/1.06*O2)+H2-V2
    qiangxian = qiangxian - (qiangxian / 1.06) * qiangxianfandian;
    shangyexian = shangyexian - (shangyexian / 1.06) * shangyefandian;
    jiachengxian = jiachengxian - (jiachengxian / 1.06) * jiachengfandian;
    value = qiangxian + shangyexian + jiachengxian + chechuanxian - yewuyuanjiangli;
  } else {
    //F2*(1-M2)+G2*(1-N2)+I2*(1-O2)+H2-V2
    qiangxian = qiangxian * (1 - qiangxianfandian);
    shangyexian = shangyexian * (1 - shangyefandian);
    jiachengxian = jiachengxian * (1 - jiachengfandian);
    value = qiangxian + shangyexian + jiachengxian + chechuanxian - yewuyuanjiangli;
  }

  const result = new Decimal(value).toFixed(2);
  var yingshjou = parseFloat(result);
  if (kaiguan.value) {
    formData.yingshou = yingshjou;
  }
};
// 监听应收相关的字段
watch(
  () => [
    formData.type,
    formData.qiangxian, //强险
    formData.shangyexian, //商业险
    formData.jiachengxian, //驾乘险
    formData.chechuanxian, //车船税
    formData.qiangxianfandian, //强险返点
    formData.shangyefandian, //商业险返点
    formData.jiachengfandian, //驾乘险返点
    formData.yewuyuanjiangli, //业务员奖励
    kaiguan.value,
  ],
  () => {
    calculateYingShou();
  }
);
// 自动返给业务员
const calculateYeWuYuan = () => {
  //=F2+G2+H2+I2-Q2+V2
  const type = Number(formData.type); // 确保转换为数字类型
  let qiangxian = formData.qiangxian || 0;
  let shangyexian = formData.shangyexian || 0;
  let jiachengxian = formData.jiachengxian || 0;
  let chechuanxian = formData.chechuanxian || 0;
  let yingshou = formData.yingshou || 0;

  let tempValue;
  if (type === 1) {
    tempValue = qiangxian + shangyexian + jiachengxian + chechuanxian;
    tempValue = tempValue - yingshou;
  } else {
    tempValue = qiangxian + shangyexian + jiachengxian + chechuanxian;
    tempValue = tempValue - yingshou;
  }
  const result = new Decimal(tempValue).toFixed(2);
  formData.fangeiyewuyuan = parseFloat(result);
};
// 监听返给业务员相关的字段
watch(
  () => [
    formData.type,
    formData.qiangxian,
    formData.shangyexian,
    formData.jiachengxian,
    formData.chechuanxian,
    formData.yingshou,
  ],
  () => {
    calculateYeWuYuan();
  }
);

const calculateTotal = () => {
  let qiangxian = formData.qiangxian || 0;
  let shangyexian = formData.shangyexian || 0;
  let jiachengxian = formData.jiachengxian || 0;
  let chechuanxian = formData.chechuanxian || 0;
  let tempValue = qiangxian + shangyexian + jiachengxian + chechuanxian;
  totalSum.value = new Decimal(tempValue).toFixed(2);
};
watch(
  () => [formData.qiangxian, formData.shangyexian, formData.jiachengxian, formData.chechuanxian],
  () => {
    calculateTotal();
  }
);

// 流水台账表单校验规则
const rules = reactive({
  salesmanName: [{ required: true, message: "请输入业务员", trigger: "blur" }],
  chepaihao: [{ required: true, message: "请输入车牌号", trigger: "blur" }],
  type: [{ required: true, message: "请选择扣税", trigger: "blur" }],
  recordDate: [{ required: true, message: "请选择日期", trigger: "blur" }],
  beibaoxianren: [{ required: true, message: "请输入被保险人", trigger: "blur" }],
});

// 处理付款状态变更的方法
function handleIsPayChange(row) {
  // 调用API更新数据
  SysLedgerAPI.update(row.id, row)
    .then(() => {
      ElMessage.success("付款状态更新成功");
      handleQuery(); // 可选：刷新列表数据
    })
    .catch((err) => {
      ElMessage.error("付款状态更新失败");
      console.error(err);
    });
}

/** 查询流水台账 */
function handleQuery() {
  loading.value = true;
  //统计
  SysLedgerAPI.getCount(queryParams).then((data) => {
    ledgerCountVO.value = data;
    console.log(ledgerCountVO.value);
  });
  SysLedgerAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置流水台账查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  recordDates.value = [getToday(), getToday()];
  queryParams.recordDate = recordDates.value;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开流水台账弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改流水台账";
    kaiguan.value = false;
    SysLedgerAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增流水台账";
  }
}

/** 提交流水台账表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        SysLedgerAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        SysLedgerAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭流水台账弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除流水台账 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      SysLedgerAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 导出用户
function handleExport() {
  SysLedgerAPI.export(queryParams).then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(response.headers["content-disposition"].split(";")[1].split("=")[1]);
    const fileType =
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}
function getToday() {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}

onMounted(() => {
  recordDates.value = [getToday(), getToday()];
  queryParams.recordDate = recordDates.value;
  handleQuery();
});
</script>
<style scoped>
:deep(.el-input-number .el-input__inner) {
  text-align: left !important;
}
</style>

<style lang="css">
.el-popper {
  max-width: 300px;
}
</style>

<style scoped>
.mb-10px {
  position: relative;
}

.ledger-count-info {
  position: absolute;
  right: 50px;
  top: -5px;
  font-size: 25px;
  font-weight: 600;
  color: #084fe7;
  text-align: center;
}
</style>

<style scoped>
.footer-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.total-sum-text {
  font-size: 25px;
  color: #084fe7;
  font-weight: 600;
}
.total-sum-text1 {
  font-size: 20px;
  color: #279b6d;
  font-weight: 600;
}
.el-switch__inner .is-text {
  color: var(--el-color-white);
  font-size: 15px;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-user-select: none;
  -moz-user-select: none;
  user-select: none;
  white-space: nowrap;
}
</style>
